import { AssetManager, assetManager } from "cc";
import { BundleName } from "../BundleName";

/**
 * 管理Bundle
 * 1. 加载Bundle
 * 2. 获取Bundle
 * 3. 移除Bundle
 */
export class BundleManager {
    private static _instance: BundleManager = null;
    public static get instance(): BundleManager {
        if (this._instance == null) {
            this._instance = new BundleManager();
        }
        return this._instance;
    }


     /**
     * 加载资源包
     * @param nameOrUrl 资源地址 / 资源包名
     * @param v         资源MD5版本号
     * @example
        var serverUrl = "http://192.168.1.8:8080/";         // 服务器地址
        var md5 = "8e5c0";                                  // Cocos Creator 构建后的MD5字符
        await bundleManager.loadBundle(serverUrl,md5);
     */
    public async loadBundle(nameOrUrl: string, v: string = null): Promise<AssetManager.Bundle> {
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(nameOrUrl, { version: v }, (err: Error | null, data: AssetManager.Bundle) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(data);
                }
            });
        });
    }

    /**
     * 获取Bundle
     * @param bundleName Bundle名称
     * @returns Bundle
     */
    public getBundle(bundleName: BundleName | string): AssetManager.Bundle | null {
        const bundle = assetManager.getBundle(bundleName);
        if (bundle) {
            return bundle;
        } else {
            console.error(`Bundle ${bundleName} 不存在, 请先加载!`);
            return null;
        }
    }

    /**
     * 移除Bundle
     * @param bundleName Bundle名称
     */
    public removeBundle(bundleName: BundleName | string) {
        const bundle = this.getBundle(bundleName);
        if (bundle) {
            assetManager.removeBundle(bundle);
        } else {
            console.error(`Bundle ${bundleName} 不存在, 不能移除!`);
        }
        console.log(`移除${bundleName}`)
    }
}

export const bundleManager = BundleManager.instance;